<?php

namespace app\common\service\platform_manage;

use app\adminapiv3\model\HostModuleRelationModel;
use app\adminapiv3\model\ServerUserGroupModel;
use app\adminapiv3\model\ServerHostGroupModuleModel;
use app\common\error_message\AuthError;
use app\common\exception\CustomException;
use app\common\service\BaseService;
use app\common\service\HostModuleRelation;
use think\Db;
use think\facade\Request;


class ServerAuthService extends BaseService
{
    /**
     * @name: 模块列表
     * @param int $host_id 主机id
     */
    public function moduleList ()
    {
        $info = Db::name('server_auth')->field('product_name')->findOrEmpty();
        if(!$info)
            return $info;
        $modules = Db::name('server_auth_module')->field('id,module_name,module_key')->select();
        foreach ($modules as &$item){
            $item['product_name'] = $info['product_name'];
        }

        return $modules;
    }

    public function findAll($field = '*')
    {
        return Db::name('server_auth')->field($field)->select();
    }


    /**
     * @name 授权列表
     * @param $params
     * @return array
     * @author wx
     * @date 2019/11/7 13:59
     */
    public function list($params, $groupId)
    {
        //查询条件
        $where[] = [
            'g.group_id','eq',$groupId
        ];
        //本次连表查询所需查询字段  server_auth.product_m_version
        $field = 'm.id,m.module_name as product_name,g.number,m.stime,g.etime,m.product_c_version';

        //条件筛选
        if(isset($params['product_name']) && !empty($params['product_name'])){
            $where[] = ['m.module_name','like','%'.$params['product_name'].'%'];
        }

        if(isset($params['stime']) && !empty($params['stime'])){
            $startTime = strtotime($params['stime']);
            $where[] = ['m.stime','between',[$startTime, $startTime + 86399]];
        }

        if(isset($params['etime']) && !empty($params['etime'])){
            $endTime = strtotime($params['etime']);
            $where[] = ['g.etime','between',[$endTime, $endTime + 86399]];
        }

        if(isset($params['number']) && is_numeric($params['number'])){
            $where[] = ['g.number', $params['number']];
        }

        $data = Db::name('server_auth_module')->alias('m')
            ->leftJoin('server_host_group_module g',"g.module_id=m.id")
            ->where($where)
            ->order('m.id desc')
            ->field($field)->paginate()->toArray();


        //查询主版本 product_m_version
        $authInfo = Db::name('server_auth')->find();

        //授权信息
        $data['authInfo'] = $authInfo;
        return $data;
    }

    /**
     * @name 查询数据
     * @param $condition
     * @param string $field
     * @return array|null|\PDOStatement|string|\think\Model
     * @author wx
     * @date 2020/4/23 16:33
     */
    public function findData($condition, $field = '*')
    {
        return Db::name('server_auth')->field($field)->where($condition)->find();
    }

    /**
     * @name: 获取模块信息
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-03 15:51:12
     */
    public function getModuleData ($moduleKey)
    {
        $return = Db::name('server_auth_module')
            ->where([
                'module_key' => $moduleKey
            ])->field('module_name,number')->find();

        if(empty($return))
        {
            throw new CustomException(AuthError::AUTHORIZED_NOT_EXIST[1], AuthError::AUTHORIZED_NOT_EXIST[0]);
        }

        return $return;
    }

    /**
     * @name: 授权剩余数量
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-03 16:01:43
     */
    public function remainingNum($moduleKey)
    {
        //获取登录用户所属资产组id
        $host_grpup_id = $this->getLoginHostGroupId();
        //查询该当前用户所属资产组的授权上限信息
        $groupModuleModel = new ServerHostGroupModuleModel();
        $limit = $groupModuleModel->getGroupAuthLimit($host_grpup_id, $moduleKey);
        if(!$limit){
            //没有当前用户所属资产组授权数据,可用授权数为0
            return 0;
        }
        $limit = $limit['number'];

        //查询该当前用户所属资产组对该模块的已授权数
        $relationModel = new HostModuleRelationModel();
        $existNum = $relationModel->getMinAuthNum($host_grpup_id, $moduleKey);
        //剩余数量 = 上限值 - 已存在数量
        $remainNum = $limit - $existNum > 0 ? $limit - $existNum : 0;
        return $remainNum;
    }

    /**
     * 检测授权时间是否已过期
     * @param string $moduleKey 模块标识
    */
    public function checkRemainTime($moduleKey){
        //当前用户所属资产组
        $host_group_id = $this->getLoginHostGroupId();

        //查询该当前用户所属资产组的授权上限信息
        $groupModuleModel = new ServerHostGroupModuleModel();
        $limit = $groupModuleModel->getGroupAuthLimit($host_group_id, $moduleKey);
        if(!$limit){
            //没有当前用户所属资产组授权数据,直接返回
            throw new CustomException(AuthError::ASSETS_GROUP_UNAUTHORIZED_MODULE[1], AuthError::ASSETS_GROUP_UNAUTHORIZED_MODULE[0]);
        }

        if($limit['etime'] && time() > $limit['etime']){
            throw new CustomException(AuthError::ASSETS_GROUP_AUTHORIZED_EXPIRED[1], AuthError::ASSETS_GROUP_AUTHORIZED_EXPIRED[0]);
        }
        return true;
    }

    /**
    * @name: 检测授权，包括数量和时间
    * @Param: 
    * @Description: 
    * @Author: foo
    * @Date: 2019-12-04 15:59:22
    */
   public function checkRemaining ($module,$count)
   {
       //检测授权时间
       $this->checkRemainTime($module);
        //检测授权数量
       $remainingNum = $this->remainingNum($module);//获取剩余授权数
       if ($remainingNum <= 0) {
           throw new CustomException(AuthError::MODULE_REMIANING_NUMBER_IS_ZERO[1], AuthError::MODULE_REMIANING_NUMBER_IS_ZERO[0]);
       }
       //如果要操作的数量 > 剩余数量 返回异常
       if($count > $remainingNum){
           throw new CustomException(AuthError::ADDED_HOST_MORE_THAN_ALLOW_AUTHORIZED[1], AuthError::ADDED_HOST_MORE_THAN_ALLOW_AUTHORIZED[0]);
       }
       return true;
   }

    /**
     * @name 获取所有需要端口配置的模块
     * @author wx
     * @date 2019/12/14 14:33
     */
   public function getAllPortMoudul()
   {
       return Db::name('server_auth')->field('product_key')->where('is_port',1)->column('product_key');
   }

   public function getModuleName($ProductKey)
   {
       return Db::name('server_auth')->where('product_key',$ProductKey)->value('product_name');
   }
}